package com.mr.xi.controller;

import com.mr.xi.service.FastDfsService;
import com.mr.xi.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Created By MrXi on 2019/12/21
 */
@Slf4j
@Api(value = "用户信息接口", tags = {"用户信息相关接口"})
@RestController
@RequestMapping("fastDfs")
public class CenterUserController {

    @Resource
    private FastDfsService fastDfsService;

    @ApiOperation(value = "用户头像修改", notes = "用户头像修改", httpMethod = "POST")
    @PostMapping("uploadFace")
    public Result uploadFace(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam String userId,
            @ApiParam(name = "file", value = "用户头像", required = true)
            MultipartFile file,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 开始文件上传
        if (file != null) {
            // 获得文件上传的文件名称
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                // 文件重命名  xxx-face.png -> ["xxx-face", "png"]
                String[] fileNameArr = fileName.split("\\.");
                // 获取文件的后缀名
                String suffix = fileNameArr[fileNameArr.length - 1];
                if (!"png".equalsIgnoreCase(suffix) &&
                        !"jpg".equalsIgnoreCase(suffix) &&
                        !"jpeg".equalsIgnoreCase(suffix) ) {
                    return Result.errorMsg("图片格式不正确！");
                }
                String storagePath = fastDfsService.upload(file, suffix);
                log.info("文件上传后的存储路径--{}",storagePath);
            }
        } else {
            return Result.errorMsg("文件不能为空！");
        }
        // 由于浏览器可能存在缓存的情况，所以在这里，我们需要加上时间戳来保证更新后的图片可以及时刷新
//        String finalUserFaceUrl = imageServerUrl + uploadPathPrefix
//                + "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
        // 更新用户头像到数据库
//        Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);
////        setNullProperty(userResult);
//        // 后续要改，增加令牌token，会整合进redis，分布式会话(修改用户信息后需重置用户的token)
//        UsersVO usersVO = conventUsersVO(userResult);
//        CookieUtils.setCookie(request, response, "user",
//                JsonUtils.objectToJson(usersVO), true);
        return Result.ok();
    }

}
